﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Leikjavefurinn.Repo;
using Leikjavefurinn.Context;

namespace Leikjavefurinn.Controllers
{
    public class TTTController : Controller
    {
        //Nýtt instance af TicTacToeRepo
        TicTacToeRepo repo = new TicTacToeRepo();

        //
        //GET : /TTT/Create
        public ActionResult Create()
        {
            TicTacToeGame game = new TicTacToeGame();
            return View(game);
        }


        [HttpPost]
        public ActionResult Create(string name)
        {
            //Tékk við óinnskráðum notendum, sendir þá á innskráningarsíðuna ef þeir reyna að búa til leik
            if (User.Identity.IsAuthenticated == false)
            {
                return RedirectToAction("Login", "Account");
            }

            //Nær í innskráðann notenda
            var user = repo.GetUser(User.Identity.Name);
            int gameId = repo.CreateGame(name, user);
            return RedirectToAction("Index", new { id = gameId });
        }

        [HandleError]
        public ActionResult Index(int id)
        {
            if (User.Identity.IsAuthenticated)
            {
                TicTacToeRepo repo = new TicTacToeRepo();
                var game = repo.GetGame(id);
                var user = repo.GetUser(User.Identity.Name);
                if (game.UserX != user.UserId)
                {
                    if (game.UserO == null)
                    {
                        ViewData["PlayerId"] = user.UserId;
                        ViewData["CurrentIndex"] = 2;

                        game.UserO = user.UserId;
                        repo.Save();
                    }
                }
                else
                {
                    ViewData["PlayerId"] = user.UserId;
                    ViewData["CurrentIndex"] = 1;
                }

                if (game != null)
                {
                    return View(game);
                }
            }
            return RedirectToAction("Create", "TTT");
        }

        public ActionResult About()
        {
            return View();
        }


    }
}
